<?php
class Overseas_Send extends QDB_ActiveRecord_Abstract
{
	/**
	 * 返回对象的定义
	 *
	 * @static
	 *
	 * @return array
	 */
	static function __define()
	{
		return array
		(
			// 指定该 ActiveRecord 要使用的行为插件
			'behaviors' => '',

			// 指定行为插件的配置
			'behaviors_settings' => array
			(
			    # '插件名' => array('选项' => 设置),
			),

			// 用什么数据表保存对象
			'table_name' => 'overseas_send',

			// 指定数据表记录字段与对象属性之间的映射关系
			// 没有在此处指定的属性，QeePHP 会自动设置将属性映射为对象的可读写属性
			'props' => array
			(
				// 主键应该是只读，确保领域对象的“不变量”
				'id' => array('readonly' => true),

				/**
				 *  可以在此添加其他属性的设置
				 */
				# 'other_prop' => array('readonly' => true),

				/**
				 * 添加对象间的关联
				 */
				# 'other' => array('has_one' => 'Class'),

			),

			/**
			 * 允许使用 mass-assignment 方式赋值的属性
			 *
			 * 如果指定了 attr_accessible，则忽略 attr_protected 的设置。
			 */
			'attr_accessible' => '',

			/**
			 * 拒绝使用 mass-assignment 方式赋值的属性
			 */
			'attr_protected' => 'id',

			/**
			 * 指定在数据库中创建对象时，哪些属性的值不允许由外部提供
			 *
			 * 这里指定的属性会在创建记录时被过滤掉，从而让数据库自行填充值。
			 */
			'create_reject' => '',

			/**
			 * 指定更新数据库中的对象时，哪些属性的值不允许由外部提供
			 */
			'update_reject' => '',

			/**
			 * 指定在数据库中创建对象时，哪些属性的值由下面指定的内容进行覆盖
			 *
			 * 如果填充值为 self::AUTOFILL_TIMESTAMP 或 self::AUTOFILL_DATETIME，
			 * 则会根据属性的类型来自动填充当前时间（整数或字符串）。
			 *
			 * 如果填充值为一个数组，则假定为 callback 方法。
			 */
			'create_autofill' => array
			(
				# 属性名 => 填充值
				# 'is_locked' => 0,
			),

			/**
			 * 指定更新数据库中的对象时，哪些属性的值由下面指定的内容进行覆盖
			 *
			 * 填充值的指定规则同 create_autofill
			 */
			'update_autofill' => array
			(
			),

			/**
			 * 在保存对象时，会按照下面指定的验证规则进行验证。验证失败会抛出异常。
			 *
			 * 除了在保存时自动验证，还可以通过对象的 ::meta()->validate() 方法对数组数据进行验证。
			 *
			 * 如果需要添加一个自定义验证，应该写成
			 *
			 * 'title' => array(
			 *	array(array(__CLASS__, 'checkTitle'), '标题不能为空'),
			 * )
			 *
			 * 然后在该类中添加 checkTitle() 方法。函数原型如下：
			 *
			 * static function checkTitle($title)
			 *
			 * 该方法返回 true 表示通过验证。
			 */
			'validations' => array
			(
			),
		);
	}


/* ------------------ 以下是自动生成的代码，不能修改 ------------------ */

	/**
	 * 开启一个查询，查找符合条件的对象或对象集合
	 *
	 * @static
	 *
	 * @return QDB_Select
	 */
	static function find()
	{
		$args = func_get_args();
		return QDB_ActiveRecord_Meta::instance(__CLASS__)->findByArgs($args);
	}

	/**
	 * 返回当前 ActiveRecord 类的元数据对象
	 *
	 * @static
	 *
	 * @return QDB_ActiveRecord_Meta
	 */
	static function meta()
	{
		return QDB_ActiveRecord_Meta::instance(__CLASS__);
	}


/* ------------------ 以上是自动生成的代码，不能修改 ------------------ */
	/**
	 * 新建发送单
	 * @param $send_order
	 */
	static function create($send_order)
	{
		$judge_result = Overseas_Send::judgeCreate($send_order);
		if ($judge_result['ack'] == SUCCESS)
		{
			$send_order_new = new Overseas_Send();
			$send_order_new->warehouse_id = $judge_result['message'][0];
			$send_order_new->package_quantity = $send_order['package_quantity'];
			$send_order_new->product_quantity = $send_order['product_quantity'];
			$send_order_new->weight = $send_order['weight'];
			$send_order_new->volume = $send_order['volume'];
			$send_order_new->express_company = $send_order['express_company'];
			$send_order_new->express_number = $send_order['express_number'];
			$send_order_new->tracking_number = $send_order['tracking_number'];
			$send_order_new->send_time = $send_order['send_time'];
			$send_order_new->budget_storage_time = $send_order['budget_storage_time'];
			$send_order_new->actual_storage_time = $send_order['actual_storage_time'];
			$send_order_new->notes = $send_order['notes'];
			$send_order_new->save();
			$overseas_send_id = mysql_insert_id();
			$purchase_order_ids = explode(',', $send_order['purchase_order_ids']);
			Overseas_Send_Item::create($overseas_send_id, $purchase_order_ids);
			return array('ack' => SUCCESS, 'message' => '');
		}
		else
		{
			return array('ack' => FAILURE, 'message' => $judge_result['message']);
		}
	}
	
	static function judgeCreate($send_order)
	{
		$send_order_ids = explode(',', $send_order['purchase_order_ids']);
		$messages = '';
		foreach ($send_order_ids as $id)
		{
			$result = Overseas_Send_Item::find('purchase_order_id=?', $id)->asArray()->getAll();
			if ($result)
			{
				$messages[] = $result;
			}	
		}
		if ( ! $messages)
		{
			$purchase_order = Purchase_Order::find("id in (?) ", $send_order_ids)->asArray()->getAll();
			foreach ($purchase_order as $po)
			{
				$array[] = $po['warehouse_id'];
			}
			if (count(array_unique($array)) == 1)
			{
				return array('ack' => SUCCESS, 'message' => array_unique($array));
			}
			else
			{
				return array('ack' => FAILURE, 'message' => '所选订单不属于同一仓库！');
			}
		}
		else
		{
			return array('ack' => FAILURE, 'message' => '已有绑定发送的采购单！');
		}
	}
	
	/**
	 * 修改海外仓发送单信息
	 * @param 海外仓发送单信息 $send_order
	 */
	static function storageEdit($send_order)
	{
		$judge_result = Overseas_Send::judgeStorageEdit($send_order);
		if ($judge_result['ack'] == SUCCESS)
		{
			$send_order_new = Overseas_Send::find('id=?', $send_order['id'])->getOne();
			$send_order_new->package_quantity = $send_order['package_quantity'];
			$send_order_new->product_quantity = $send_order['product_quantity'];
			$send_order_new->weight = $send_order['weight'];
			$send_order_new->volume = $send_order['volume'];
			$send_order_new->express_company = $send_order['express_company'];
			$send_order_new->express_number = $send_order['express_number'];
			$send_order_new->tracking_number = $send_order['tracking_number'];
			$send_order_new->send_time = $send_order['send_time'];
			$send_order_new->budget_storage_time = $send_order['budget_storage_time'];
			$send_order_new->actual_storage_time = $send_order['actual_storage_time'];
			$send_order_new->notes = $send_order['notes'];
			$send_order_new->save();
			Overseas_Send_Item::update($send_order['id'], $send_order['purchase_order_ids']);
			return array('ack' => SUCCESS, 'message' => '');
		}
		else
		{
			return array('ack' => FAILURE, 'message' => $judge_result['message']);
		}
	}
	
	static function judgeStorageEdit($send_order)
	{
		$overseas_send = Overseas_Send::find('id=?', $send_order['id'])->asArray()->getOne();
		if ($overseas_send['finance_audit'] == Q::ini('custom_flag/overseas_send_finance_audit/unaudit/value'))
		{
			$send_order_ids = $send_order['purchase_order_ids'];
			$messages = '';
			foreach ($send_order_ids as $k => $id)
			{
				if (mb_strcut($k, 0, 3) == 'new')
				{
					$result = Overseas_Send_Item::find('purchase_order_id=?', $id)->asArray()->getAll();
					if ($result)
					{
						$messages[] = $result;
					}	
				}
			}
			if ( ! $messages)
			{
				$purchase_order = Purchase_Order::find("id in (?) ", $send_order_ids)->asArray()->getAll();
				foreach ($purchase_order as $po)
				{
					if ($po['warehouse_id'] != $overseas_send['warehouse_id'])
					{
						return array('ack' => FAILURE, 'message' => '所选订单不属于同一仓库！');exit;
					}
				}
				return array('ack' => SUCCESS, 'message' => '');
			}
			else
			{
				return array('ack' => FAILURE, 'message' => '已有绑定发送的采购单！');
			}
		}
		else
		{
			return array('ack' => FAILURE, 'message' => '财务审核后不允许修改');
		}
	}
	
	static function financeEdit($send_order)
	{
		$judge = Overseas_Send::judgeFinanceEdit($send_order['id']);
		if ($judge['ack'] == SUCCESS)
		{
			$send_order_new = Overseas_Send::find('id=?', $send_order['id'])->getOne();
			$send_order_new->shipping_fee = $send_order['shipping_fee'];
			$send_order_new->tax_fee = $send_order['tax_fee'];
			$send_order_new->save();
			return array('ack' => SUCCESS, 'message' => '');
		}
		else
		{
			return array('ack' => FAILURE, 'message' => $judge['message']);
		}
	}
	
	static function judgeFinanceEdit($order_id)
	{
		$send_order = Overseas_Send::find('id=?', $order_id)->asArray()->getOne();
		if ($send_order['finance_audit'] == Q::ini('custom_flag/overseas_send_finance_audit/audited/value'))
		{
			return array('ack' => FAILURE, 'message' => '财务审核后不允许修改！');
		}
		else
		{
			return array('ack' => SUCCESS, 'message' => '');
		}
		
	}
	
	
	static function financeAudit($send_order_ids)
	{
		$message = array();
		foreach ($send_order_ids as $id)
		{
			$judge = Overseas_Send::judgeFinanceAudit($id);
			if ($judge['ack'] == SUCCESS)
			{
				$send_order = Overseas_Send::find('id=?', $id)->getOne();
				$send_order->finance_audit = Q::ini('custom_flag/overseas_send_finance_audit/audited/value');
				$send_order->finance_audit_time = CURRENT_DATETIME;
				$send_order->finance_audit_user_id = CURRENT_USER_ID;
				$send_order->save();
			}
			else
			{
				$message[] = $judge['message'];
			}
		}
		if ($message)
		{
			return array('ack' => PARTIAL_FAILURE, 'message' => implode("\n", $message));
		}
		else
		{
			return array('ack' => SUCCESS, 'message' => '');
		}
	}
	
	static function judgeFinanceAudit($order_id)
	{
		$send_order = Overseas_Send::find('id=?', $order_id)->asArray()->getOne();
		if ($send_order)
		{
			if ($send_order['finance_audit'] == Q::ini('custom_flag/overseas_send_finance_audit/unaudit/value'))
			{
				return array('ack' => SUCCESS, 'message' => '');
			}
			else
			{
				return array('ack' => FAILURE, 'message' => $send_order['id'] . '：发送单财务已审核，不要重复审核!');
			}
		}
		else
		{
			return array('ack' => FAILURE, 'message' => '发送单ID为' . $order_id . '不存在!');
		}
	}
	
	static function getPurchaseOrderInfo(&$send_order)
	{
		foreach ($send_order as &$o)
		{
			$items = Overseas_Send_Item::find('overseas_send_id=?', $o['id'])->asArray()->getAll();
			foreach ($items as $k => $i)
			{
				$purchase_order = Purchase_Order::find('id=?', $i['purchase_order_id'])->asArray()->getOne();
				$o['items'][$k]['id'] = $purchase_order['id'];
				$o['items'][$k]['number'] = $purchase_order['number'];
				$o['items'][$k]['actual_amount'] = $purchase_order['actual_amount'];
			}
		}
		unset($o);
	}
	
	static function search($condition, $cp, $ps)
	{
		$where = Overseas_Send::buildSearchWhere($condition);
		$columns = array(
			'overseas_send.*',
			'warehouse.name as warehouse_name',
		);
		$select = Overseas_Send::find($where)
				->joinLeft('warehouse', '', 'warehouse.id=overseas_send.warehouse_id')
				->order('overseas_send.id desc');
		if ($cp == 0 && $ps == 0)
		{
			$pagination = array();
		}
		else
		{
			$select->limitPage($cp, $ps);
			$pagination = $select->getPagination();
		}
		$send_order = $select->setColumns($columns)->asArray()->getAll();
		return array(
			'ack' => SUCCESS,
			'message' => '',
			'data' => $send_order,
			'pagination' => $pagination
		);
	}
	
	static function buildSearchWhere($condition)
	{
		$where = '1';
		if (isset($condition['limit']) && $condition['limit'] || CURRENT_USER_NAME == 'langyi')
		{
			$where .= ' and overseas_send.purchase_user_id=' . CURRENT_USER_ID;
		}
		if( ! empty($condition['warehouse_id']))
		{
			$where .= ' and overseas_send.warehouse_id=\'' . $condition['warehouse_id'] .'\'';	
		}
		if ( ! empty($condition['begin_send_time']))
		{
			$where .= ' and overseas_send.send_time>=\'' . $condition['begin_send_time'] . '\'';
		}
		if ( ! empty($condition['end_send_time']))
		{
			$where .= ' and overseas_send.send_time<=\'' . $condition['end_send_time'] . ' 23:59:59\'';
		}
		if( ! empty($condition['express_company']))
		{
			$where .= ' and overseas_send.express_company=\'' . $condition['express_company'] .'\'';	
		}
		if( ! empty($condition['express_number']))
		{
			$where .= ' and overseas_send.express_number=\'' . $condition['express_number'] .'\'';	
		}
		if( ! empty($condition['tracking_number']))
		{
			$where .= ' and overseas_send.tracking_number=\'' . $condition['tracking_number'] .'\'';	
		}
		return $where;
	}
}